<template>
  <JVxeTable
    ref="tableRef"
    stripe
    toolbar
    keepSource
    rowNumber
    rowSelection
    asyncRemove
    dragSort
    :sync-resize="activeKey"
    :maxHeight="700"
    :checkboxConfig="{range: true}"
    :disabledRows="{ isPk: [true] }"
    :loading="loading"
    :disabled="disabled"
    :columns="columns"
    :dataSource="dataSource"
    @removed="handleRemoved"
  >
  </JVxeTable>
</template>

<script lang="ts" setup>
  import {ref, computed, onMounted, watch, defineProps, defineExpose, unref} from 'vue';
  import { Popconfirm } from 'ant-design-vue'
  import { JVxeTypes, JVxeColumn, JVxeTableInstance } from '/@/components/jeecg/JVxeTable/types'
  import { listGenTableIndex, batchDeleteGenTableIndex } from '../../codeGen.api'
  import { tableIndexColumns } from '../../codeGen.data'
  import { pushIfNotExist } from '/@/utils/common/compUtils';
  import { useMessage } from '/@/hooks/web/useMessage'
  const { createMessage } = useMessage()
  const tableRef = ref<JVxeTableInstance>()
  const loading = ref(false)
  const disabled = ref(false)

  const dataSource = ref<Recordable[]>([])

  const props = defineProps({
    // 子组件接收父组件传递过来的值
    rowId: String,
    tableColumns: Object,
    activeKey: String
  })
  /**
   * 页面信息配置
   */
  const columns = computed<JVxeColumn[]>(() => {
    console.log("record: ", props.tableColumns)
    let indexOptions: any = []
    props.tableColumns?.forEach(x => {
      indexOptions.push({ title: x.columnName, value: x.columnName})
    })
    return [
      // 表的索引记录id
      { title: 'ID', key: 'id', type: JVxeTypes.hidden },
      { title: 'tableId', key: 'tableId', type: JVxeTypes.hidden },
      {
        title: '索引名称', key: 'name', type: JVxeTypes.input, width: 180,
        validateRules: [{ required: true, message: '${title}不能为空' }],
      },
      {
        title: '索引类型', key: 'type', type: JVxeTypes.select, width: 180,
        options: [], dictCode: 'mysql_table_index_type', placeholder: '请选择'
      },
      {
        title: '索引方法', key: 'method', type: JVxeTypes.select, width: 180,
        options: [], dictCode: 'mysql_table_index_method', placeholder: '请选择'
      },
      {
        title: '索引字段', key: 'columnNames', type: JVxeTypes.selectMultiple, width: 360, allowSearch: true,
        options: indexOptions, 
        placeholder: '请选择',
        validateRules: [{ required: true, message: '${title}不能为空' }],
      },
      { title: '备注', key: 'comment', type: JVxeTypes.input, width: "35%", defaultValue: ''},
    ]
  })

  const validate = async (callback: Function) => {
    const values = tableRef.value!.getTableData()
    // 必须先一行一行的校验找到校验失败的行, 然后调用 参数 callback, 让用户切换标签
    // 再调用validateTable()进行二次校验找到具体的行(会有校验失败的消息提示)

    // 如果你直接调用 validateTable() 进行校验, 校验完之后在切换标签会导致页面出现问题
    // 比如消息提示跑到左上角了, 表格也是有问题的
    for(const item in values) {
      const errMap = await tableRef.value!.validateTable(values[item])
      if (errMap) {
        console.log("校验失败的行: ", values[item])
        console.log('表单验证未通过：', { errMap });
        if (callback) {
          callback()
        }
        // 这块再校验一边的原因是提示是哪一行校验失败
        await tableRef.value!.validateTable()
        return false
      } 
    } 
    return true
  }

  const getData = () => {
    const data = tableRef.value!.getTableData()
    data.forEach(x => {
      x['tableId'] = props.rowId
    })
    return data
  }

  watch(
    () => props.rowId,
    async (val) => {
      try {
        if (val) {
          console.log("rowId: ", val)
          dataSource.value = []
          loading.value = true
          const result = await listGenTableIndex(unref(val))
          dataSource.value = result
        }
      } catch(err) {
        console.error(err)
      } finally {
        loading.value = false
      }
    },
    { deep: true, immediate: true }
  );

  const handleRemoved = async (event) => {
    const hideLoading = createMessage.loading('删除中…', 0);
    try {
      // 1. 向后台传递 event.deleteRows 以删除
      let ids = []
      event.deleteRows.forEach(x => {
       if (!x.id.includes("row")) {
        ids.push(x.id)
       }
      })
      if (ids.length == 0) {
        return
      }
      console.log("delete ids: ", ids)
      await batchDeleteGenTableIndex(ids)
      // await event.confirmRemove()
      createMessage.success('删除成功！');
    } catch(e) {
      createMessage.warn('删除失败！');
    } finally {
      await tableRef.value!.removeSelection();
      hideLoading();
    }
  }

  defineExpose({getData, validate})
</script>